package com.book.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.mapper.OrderMapper;
import com.book.pojo.CartVo;
import com.book.pojo.Order;
import com.book.pojo.OrderItem;
import com.book.pojo.User;
import com.book.utils.OrderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private CartService cartService;

    //购买
    public String buy(List<CartVo> cartVos, Integer addrId, Integer status, HttpSession session){

        User user = (User)session.getAttribute("user");

        //1.生成订单表记录
        Order order = new Order();
        order.setAddressId(addrId);
        order.setUserId(user.getId());
        order.setCreateDate(new Date());
        //order.setOrderNum(UUID.randomUUID().toString());
        order.setOrderNum(OrderUtils.createOrderNum()); //自定义订单编号
        //TODO 订单状态，0已经付款，1未付款（根据前端传过来的status）
        order.setOrderStatus(String.valueOf(status));  //订单状态 先写个 1
        orderMapper.insert(order);  //插入数据

        //2.生成订单明细表记录
        List<OrderItem> orderItems = new ArrayList<>();
        List<Integer> cartIds = new ArrayList<>();  //购物车对应物品的id，为了后续删除操作
        for (CartVo cartVo : cartVos) {
            OrderItem orderItem = new OrderItem(); //明细
            orderItem.setBookId(cartVo.getBookId());
            orderItem.setOrderId(order.getId());
            orderItem.setCount(cartVo.getCount());

            orderItems.add(orderItem);

            cartIds.add(cartVo.getId());  //获取购物车id
        }
        orderItemService.saveBatch(orderItems);

        //3.删除购物车表记录
        cartService.removeByIds(cartIds);

        return "success";
    }


    //查询用户订单
    public List<Order> findUserOrder(Integer userId){
        return orderMapper.findOrderAndOrderDetailByUserId(userId);
    }
}
